import { ref, onMounted } from 'vue'
import _ from 'lodash'
// import {ElMessageBox, ElMessage} from 'element-plus'

import useDialog from '@/hook/useDialog'

export default function useFormDialog(
  proxy,
  options = {
    formRef: undefined,
    idProp: 'id',

    handleAdd: { before: undefined },
    handleCopyAdd: { before: undefined },
    add: {
      action: undefined,
      before: undefined,
      after: undefined,
      resolveParam: undefined,
      defaultData: undefined,
      title: '添加记录',
      tips: '添加成功'
    },

    handleEdit: { before: undefined },
    edit: {
      action: undefined,
      defaultData: undefined,
      resolveParam: undefined,
      title: '编辑记录',
      tips: '更新成功'
    },

    submit: { before: undefined, after: undefined, resolveParam: undefined },

    handleCancel: { after: undefined }
  }
) {
  const addOptions = {
    open: {
      before: options.handleAdd?.before,
      type: 'add',
      title: '添加记录'
    },
    close: {
      after: options.handleCancel?.after
    },
    submit: {
      action: options.add.action,
      before: options.add?.before,
      after: options.add?.after,
      validRef: options.formRef,
      resolveParam: options.add?.resolveParam,
      tips: options.add?.tips
    }
  }

  const {
    dialogModel,
    handleOpen: handleAdd,
    handleClose: handleClose,
    handleSubmit: handleSubmitAdd
  } = useDialog(proxy, addOptions)

  const editForm = ref({
    show: false,
    // add edit
    type: '',
    title: '',
    data: {},
    submitLoading: false
  })

  // function handleAdd() {
  //   if (_.isFunction(options.handleAdd?.before)) {
  //     options.handleAdd.before()
  //   }
  //   editForm.value.type = 'add'
  //   editForm.value.title = options.add?.title || '添加记录'
  //   editForm.value.data = defaultAddFormData()
  //   if (_.isFunction(options.handleAdd?.after)) {
  //     options.handleAdd.after()
  //   }
  //   editForm.value.show = true
  // }

  // function handleCopyAdd(copyData) {
  //   if (_.isFunction(options.handleCopyAdd?.before)) {
  //     options.handleCopyAdd.before()
  //   }
  //   editForm.value.type = 'add'
  //   editForm.value.title = options.add?.title || '添加记录'
  //   editForm.value.data = _.merge(defaultEditFormData(), copyData)
  //   editForm.value.data[options.idProp ? options.idProp : 'id'] = undefined
  //   if (_.isFunction(options.handleCopyAdd?.after)) {
  //     options.handleCopyAdd.after()
  //   }
  //   editForm.value.show = true
  // }

  function handleEdit(editData) {
    if (_.isFunction(options.handleEdit?.before)) {
      options.handleEdit.before()
    }
    editForm.value.type = 'edit'
    editForm.value.data = _.merge(defaultEditFormData(), editData)
    editForm.value.title =
      '编辑记录：' + (editForm.value.data[options.edit.titleProp] || '')
    if (_.isFunction(options.handleEdit?.after)) {
      options.handleEdit.after()
    }
    editForm.value.show = true
  }

  // function handleCancel() {
  //   if (_.isFunction(options.handleCancel?.before)) {
  //     options.handleCancel.before()
  //   }
  //   handleClose()
  //   if (_.isFunction(options.handleCancel?.after)) {
  //     options.handleCancel.after()
  //   }
  // }

  function handleClose() {
    editForm.value.show = false
    resetForm()
  }

  function resetForm() {
    // dialog没渲染$refs获取不到值
    proxy.$refs[options.formRef]?.resetFields()

    if (editForm.value.type === 'add') {
      editForm.value.data = defaultAddFormData()
    } else if (editForm.value.type === 'edit') {
      editForm.value.data = defaultEditFormData()
    } else {
      editForm.value.data = {}
    }
  }

  function openForm() {
    editForm.value.show = true
  }

  function handleSubmit() {
    // ElMessage({
    //   message: '测试异常',
    //   type: 'error'
    // })
    // return;
    if (_.isFunction(options.submit?.before)) {
      options.submit.before()
    }
    if (Object.keys(editForm.value.data).length === 0) {
      // todo 空对象警告
      console.warn(editForm.value.data, 'form data is empty')
      return
    }

    editForm.value.submitLoading = true
    proxy.$refs[options.formRef].validate((valid, prop) => {
      if (!valid) {
        editForm.value.submitLoading = false
        console.warn(prop, 'valid failed')
        return
      }

      const param = _.isFunction(options.submit?.resolveParam)
        ? options.submit.resolveParam(editForm.value.data)
        : editForm.value.data
      // 判断新增还是更新
      if (editForm.value.type === 'add') {
        options.add
          .action(param)
          .then((res) => {
            editForm.value.submitLoading = false
            if (_.isFunction(options.submit?.after)) {
              options.submit.after(res)
            }
            handleClose()
            proxy.$modal.msgSuccess(options.add.tips || '添加成功!')
          })
          .catch((e) => {
            editForm.value.submitLoading = false
            // console.error(e, 'submit error')
          })
      } else {
        options.edit
          .action(param)
          .then((res) => {
            editForm.value.submitLoading = false
            if (_.isFunction(options.submit?.after)) {
              options.submit.after(res)
            }
            handleClose()
            proxy.$modal.msgSuccess(options.edit.tips || '修改成功!')
          })
          .catch((e) => {
            editForm.value.submitLoading = false
            // console.error(e, 'submit error')
          })
      }
    })
  }

  function defaultAddFormData() {
    return options.add.defaultData ? _.cloneDeep(options.add.defaultData) : {}
  }

  function defaultEditFormData() {
    return options.edit.defaultData ? _.cloneDeep(options.edit.defaultData) : {}
  }

  onMounted(() => {
    console.log('useForm hook mounted!')
  })

  return {
    editForm,
    handleAdd,
    handleCopyAdd,
    handleEdit,
    handleCancel,
    handleClose,
    openForm,
    resetForm,
    handleSubmit
  }
}
